package com.mikey.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author :Mikey
 * @description : 求和计算
 * 使用forkjoin   或者并行流（牛逼）
 * 如何使用forkjoin
 * 1.forkjoinpool  通过他来执行
 * 2.计算任务forkjoinPool.execute（ForkjoinTask task）
 * @create :2022-09-22 15:40:00
 */
public class Demo extends RecursiveTask<Long> {
    private long start;
    private long end;
    private long temp = 10000L;//临界值

    public Demo(long satrt, long end) {
        this.start = satrt;
        this.end = end;
    }

    //计算方法
    @Override
    protected Long compute() {
        if (end - start < temp) {
            long sum = 0l;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {//forkjoin
            long middle = (start + end) / 2;
            Demo demo = new Demo(start, middle);
            demo.fork();//拆分任务，把任务压入线程队列
            Demo demo1 = new Demo(start, middle);
            demo1.fork();
            long l = demo.join() + demo1.join();
            return l;
        }
    }
}
